package com.achievement.project.system.score.service.impl;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import com.achievement.common.exception.BusinessException;
import com.achievement.common.utils.StringUtils;
import com.achievement.common.utils.security.ShiroUtils;
import com.achievement.project.system.choose.domain.CourseChoose;
import com.achievement.project.system.choose.mapper.CourseChooseMapper;
import com.achievement.project.system.config.service.IConfigService;
import com.achievement.project.system.course.domain.Course;
import com.achievement.project.system.course.mapper.CourseMapper;
import com.achievement.project.system.proranking.domain.Proranking;
import com.achievement.project.system.proranking.mapper.ProrankingMapper;
import com.achievement.project.system.student.domain.Student;
import com.achievement.project.system.student.mapper.StudentMapper;
import com.achievement.project.system.user.domain.User;
import com.achievement.project.system.user.service.UserServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.achievement.project.system.score.mapper.ScoreMapper;
import com.achievement.project.system.score.domain.Score;
import com.achievement.project.system.score.service.IScoreService;
import com.achievement.common.utils.text.Convert;

/**
 * 成绩详情页面Service业务层处理
 *
 * @author zkai
 * @date 2021-04-24
 */
@Service
public class ScoreServiceImpl implements IScoreService
{
    private static final Logger log = LoggerFactory.getLogger(ScoreServiceImpl.class);
    @Autowired
    private ScoreMapper scoreMapper;
    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseChooseMapper courseChooseMapper;
    @Autowired
    private ProrankingMapper prorankingMapper;

    @Autowired
    private IConfigService configService;
    /**
     * 查询成绩详情页面
     *
     * @param id 成绩详情页面ID
     * @return 成绩详情页面
     */
    @Override
    public Score selectScoreById(Long id)
    {
        return scoreMapper.selectScoreById(id);
    }

    /**
     * 查询成绩详情页面列表
     *
     * @param score 成绩详情页面
     * @return 成绩详情页面
     */
    @Override
    public List<Score> selectScoreList(Score score)
    {
        return scoreMapper.selectScoreList(score);
    }

    @Override
    public List<Score> selectScoreListForExcel(Score score) {
        return scoreMapper.selectScoreListForExcel(score);
    }

    /**
     * 新增成绩详情页面
     *
     * @param score 成绩详情页面
     * @return 结果
     */
    @Override
    public int insertScore(Score score)
    {
        return scoreMapper.insertScore(score);
    }

    /**
     * 修改成绩详情页面
     *
     * @param score 成绩详情页面
     * @return 结果
     */
    @Override
    public int updateScore(Score score)
    {
        CourseChoose courseChoose = courseChooseMapper.selectCourseChooseById(Integer.parseInt(score.getCourseId().toString()));
        if (Integer.parseInt(score.getScore())>=60){
            score.setCredit(courseChoose.getCredit());
            score.setScoreStatus("1");
            if (StringUtils.isEmpty(score.getPoint())){
                BigDecimal point = BigDecimal.valueOf((Integer.parseInt(score.getScore())-50)).divide(BigDecimal.valueOf(10),2,BigDecimal.ROUND_UNNECESSARY);
            //  point = point.divide(point,2,BigDecimal.ROUND_UNNECESSARY);
                score.setPoint(String.valueOf(point));
            }
        }else if(Integer.parseInt(score.getScore())>50&&Integer.parseInt(score.getScore())<60){
            score.setCredit("0");
            score.setScoreStatus("0");
                BigDecimal point = BigDecimal.valueOf((Integer.parseInt(score.getScore())-50)).divide(BigDecimal.valueOf(10),2,BigDecimal.ROUND_UNNECESSARY);
                //  point = point.divide(point,2,BigDecimal.ROUND_UNNECESSARY);
                score.setPoint(String.valueOf(point));
        } else {
            score.setCredit("0");
            score.setScoreStatus("0");
            score.setPoint("0");
        }
        //将绩点和得分插入表中
        int i = scoreMapper.updateScore(score);
        Score scTemp = scoreMapper.selectScoreById(score.getId());
        if (i>0){
            List<Map<String, Object>> ranking = scoreMapper.getRanking(scTemp.getTeacherId());

            for (Map<String, Object> map:ranking
            ) {
                Score s = new Score();
                s.setId(Long.parseLong(map.get("id").toString()));
                s.setRanking(map.get("rownum").toString());
                scoreMapper.updateScore(s);
            }
            //将专业排名通过计算同样插入到分数表中
            List<Map<String, Object>> pranking = scoreMapper.getPranking(Long.valueOf(scTemp.getProfessionalId()));

            for (Map<String, Object> map:pranking
            ) {
                Score s = new Score();
                s.setId(Long.parseLong(map.get("id").toString()));
                s.setpRanking(map.get("rownum").toString());
                scoreMapper.updateScore(s);
            }
        }
        return scoreMapper.updateScore(score);
    }

    /**
     * 删除成绩详情页面对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteScoreByIds(String ids)
    {
        prorankingMapper.deleteProrankingBySno(Long.valueOf(ids));
        return scoreMapper.deleteScoreByIds(Convert.toStrArray(ids));
    }

    @Override
    public int deleteScoreByCourse(Long studentId,Long courseId) {
        return scoreMapper.deleteScoreByCourse(studentId,courseId);
    }

    /**
     * 删除成绩详情页面信息
     *
     * @param id 成绩详情页面ID
     * @return 结果
     */
    @Override
    public int deleteScoreById(Long id)
    {
        return scoreMapper.deleteScoreById(id);
    }

    @Override
    public List<Map<String, Object>> getRanking(Long teacherId) {
        return scoreMapper.getRanking(teacherId);
    }

    @Override
    public List<Map<String, Object>> getPranking(Long professionalId) {
        return scoreMapper.getPranking(professionalId);
    }

    /**
     * 导入用户数据
     *
     * @param scoreList 成绩数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Override
    public String importUser(List<Score> scoreList, Boolean isUpdateSupport)
    {
        if (StringUtils.isNull(scoreList) || scoreList.size() == 0)
        {
            throw new BusinessException("导入学生成绩数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String operName = ShiroUtils.getLoginName();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (Score score : scoreList)
        {
            try
            {


                // 验证是否存在这个学生
                score.setTeacherId(ShiroUtils.getUserId());
                List<Score> u = scoreMapper.selectScoreListIsExist(score);
                if (u.size()==0)
                {
                    //不存在即 同时在学生表  课程与学生关联表  成绩表增加数据
                    Student student = new Student();
                    student.setNo(score.getSno());
                    student.setName(score.getSname());
                    student.setPassword(password);
                    student.setGradeId(Long.valueOf(score.getGradeId()));
                    student.setProfessionalId(Long.valueOf(score.getProfessionalId()));
                    student.setClassId(Long.valueOf(score.getClassId()));
                    student.setSemester(score.getSemester());
                    //现将学生信息插入学生表中
                    studentMapper.insertStudent(student);
                    //获取插入表中学生的id
                    Integer lastInsertId = studentMapper.lastInsertId();
                    //根据课程名称查询课程情况
                    CourseChoose courseChoose = courseChooseMapper.getCourseByName(score.getCourseName());
                    Course course = new Course();
                    course.setsId(Long.valueOf(lastInsertId));
                    course.setpId(courseChoose.getTeacherId());
                    course.setcTypeId(Long.valueOf(courseChoose.getCourseType()));
                    course.setCourseId(Long.valueOf(courseChoose.getCourseId()));
                    //在课程和中间表中插入数据
                    courseMapper.insertCourse(course);
                    score.setStudentId(Long.valueOf(lastInsertId));
                    score.setTeacherId(Long.valueOf(courseChoose.getTeacherId()));
                    score.setCourseId(Long.valueOf(courseChoose.getCourseId()));
                    score.setcTypeId(Long.valueOf(courseChoose.getCourseType()));
                    score.setStudentId(Long.valueOf(lastInsertId));
                    //数据插入成绩表中
                    this.insertScore(score);
                    //获取插入表中的数据的id
                    Integer integer = scoreMapper.lastInsertId();
                    score.setId(Long.valueOf(integer));
                    this.updateScore(score);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、成绩 " + score.getSname() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    Student student = new Student();
                    student.setId(u.get(0).getStudentId());
                    student.setNo(score.getSno());
                    student.setName(score.getSname());
                    student.setGradeId(Long.valueOf(score.getGradeId()));
                    student.setProfessionalId(Long.valueOf(score.getProfessionalId()));
                    student.setClassId(Long.valueOf(score.getClassId()));
                    student.setSemester(score.getSemester());
                    //现将学生信息插入学生表中
                    studentMapper.updateStudent(student);
                    //根据课程名称查询课程情况
                    CourseChoose courseChoose = courseChooseMapper.getCourseByName(score.getCourseName());
                    Course course = new Course();
                    course.setsId(u.get(0).getStudentId());
                    course.setpId(courseChoose.getTeacherId());
                    course.setcTypeId(Long.valueOf(courseChoose.getCourseType()));
                    course.setCourseId(Long.valueOf(courseChoose.getCourseId()));
                    //在课程和中间表中插入数据
                    courseMapper.updateCourse(course);
                    score.setCourseId(Long.valueOf(courseChoose.getCourseId()));
                    score.setcTypeId(Long.valueOf(courseChoose.getCourseType()));
                    score.setId(u.get(0).getId());
                    this.updateScore(score);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、成绩 " +score.getSname()+ " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、成绩 " + score.getSname() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、成绩 " + score.getSname() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new BusinessException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    @Override
    public List<Map<String,Object>> getEchartsForPolyline(Long teacherId) {
        return scoreMapper.getEchartsForPolyline(teacherId);
    }
}
